<template>
  <div>
    <el-skeleton :loading="data_loading" animated :throttle="100">
      <template slot="template">
        <div style="display:flex;text-align: center;margin: 0 auto">
          <el-row v-for="item,index in [1,2,3,4,5,6]" :key="index" style="margin: 20px">
            <el-skeleton-item variant="image" style="width: 230px; height: 230px;"/>
            <el-col style="padding: 15px;">
              <el-skeleton-item variant="h3" style="width: 100%;" />
              <div style="display: flex; align-items: center; justify-items: space-between; margin-top: 16px; height: 16px;"></div>
            </el-col>
          </el-row >
        </div>
        <div style="display:flex;text-align: center;margin: 0 auto">
          <el-row v-for="item,index in [1,2,3,4,5,6]" :key="index" style="margin: 20px">
            <el-skeleton-item variant="image" style="width: 230px; height: 230px;"/>
            <el-col style="padding: 15px;">
              <el-skeleton-item variant="h3" style="width: 100%;" />
              <div style="display: flex; align-items: center; justify-items: space-between; margin-top: 16px; height: 16px;"></div>
            </el-col>
          </el-row >
        </div>
      </template>
      <template>
        <el-row v-show="showTable" style="margin: 30px auto;text-align:center;">
          <el-col class="margin_top" v-for="item,index in table_arr" :key="index" :span="table">
            <img @click="webTable(item)" src="@/static/img/表格.png" alt="">
            <p @click="webTable(item)">{{item}}</p>
          </el-col>
        </el-row>
      </template>
    </el-skeleton>
    <div v-if="!showTable" class="data">
        <el-table
        style="width: 100%"
        ref='multipleTable'
        @row-click="handleCurrentChange"
        @selection-change="selection"
        highlight-current-row
        :header-cell-style="{ backgroundColor: '#eaecf1', color: '#003d74' }"
        :row-style="rowstyles"
        :data="tableData"
        >
        <el-table-column type="selection" width="55"> </el-table-column>
        <!-- 循环显示字段数据 -->
        <div v-for="item,index in TableArr" :key="index">
          <!-- 仅展示******字符 -->
          <el-table-column :label="item" v-if="item!='pass'&&item!='delete'" :prop="item" ></el-table-column>
        </div>

        </el-table>
        <el-pagination
        style="text-align: center;position: absolute;bottom:2%;left:50%;transform: translateX(-50%);" background
        :hide-on-single-page="hidden_one"
        layout="prev, pager, next"
        :page-size="onepage_number"
        @current-change="clickPage"
        :total="page_all_number"
        >
        </el-pagination>
        <el-button
            class="someDelete"
            size="mini"
            type="danger"
            @click="someDelete"
            >删除
        </el-button>
        <el-button class="add" type="danger" @click="addManage=true" >添加数据 </el-button>
      <!-- 添加数据弹出框 -->
      <el-dialog :visible.sync="addManage" width="60%">
        <div style="text-align:left;width:85%;margin: 20px auto;font-size:23px">添加数据</div>
        <el-form :model="ruleData" status-icon ref="ruleData" label-width="100px" class="demo-ruleForm">
          <div v-for="item,index in dateArr" :key="index">
            <el-form-item v-if="item!='id'&&item!='delete'" :label="item" :prop="item" :rules="[  { required: true, message: '不为空', trigger: 'blur' }]">
              <el-input type="text" v-model="ruleData[item]" autocomplete="off"></el-input>
            </el-form-item>
          </div>
          <span>
            <el-button @click="addManage = false">取 消</el-button>
            <el-button type="primary" @click="addForm('ruleData')">添 加</el-button>
          </span>
        </el-form>
      </el-dialog>
    </div>
  </div>
</template>

<script>
export default {
  data(){
    return{
      showTable:true,
      table:4,
      table_arr:[],
      dataName:"",
      tableName:"",
      page_index: 1,
      tableData: [],
      TableArr:[],
      dateArr:[],
      search: "",
      currentRow: null,
      hidden_one: false,
      page_all_number:10,
      onepage_number: 9,
      multipleSelection: [],
      addManage:false,
      ruleData:'',
      setInter:"",
      data_loading:true,
    }
  },
  methods:{
    webTable(item){
      this.tableName=item
      this.data_loading=true //开启加载骨架
      //隐藏表界面,获取表的数据并显示在页面上
      this.ruleData=[]
      console.log(this.dataName,item,this.page_index,this.onepage_number)
      this.$axios.get(`api/webTableData?name=${this.dataName}&table=${item}&page=${this.page_index}&number=${this.onepage_number}`).then(async (data)=>{
        this.tableData=await data.data.data
        console.log(data.data.max)
        this.page_all_number=await data.data.max
        //"id","goods","price","goods_sort","goods_order"
        let ii=""
        for(let i in this.tableData[0]){
          this.TableArr.push(i)
          this.dateArr.push(i)
          if(i=='id'||i=='delete'){

          }else {
            this.ruleData.push('"'+i+'":""')
            ii=i
          }
        }
        this.ruleData=await JSON.parse('{'+(this.ruleData.join(",",","))+'}')
        console.log(this.ruleData);
      })

      this.$store.commit("setWeb_table",item)
      setTimeout(()=>{
        this.data_loading=false //关闭加载骨架
        this.showTable=false
      },1500)
    },
    rowstyles({ row, rowIndex }) {  //每行样式
      let aa = {
        "background-color": "#eaecf1",
        color: "#000000",
      };
      return aa;
    },
    handleCurrentChange(row) {  //点击勾选或取消
      for(let i=0;i<this.tableData.length;i++){
        if(row.id==this.tableData[i].id){
            this.$refs.multipleTable.toggleRowSelection(this.tableData[i]);
        }
      }
    },
    searchinput(){  //查询方法，循环判断查询
        clearInterval(this.setInter)
        setInterval(()=>{
          //延迟查询

        },500)
    },
    selection(res){ //勾选状态每次改变时触发，存储勾选那一行的数据
      let arr=[]
      for(let i=0;i<res.length;i++){
        arr.push(res[i].id)
      }
      console.log(res,arr)
      this.multipleSelection=arr
    },
    someDelete() {  //删除后刷新一遍
       //获取要删除的数据
       console.log(this.multipleSelection)
      if(this.multipleSelection==""){
        this.$message({
            type: 'error',
            message: '没有选中任何选项'
          });
      }else {
        this.$confirm('此操作将删除所有选中记录, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          //向后端请求批量删除
          let type_,msg
          this.$axios.get(`api/webTableDelete?name=${this.dataName}&table=${this.tableName}&page=${this.page_index}&number=${this.onepage_number}&id=${this.multipleSelection}`).then(async (data)=>{
              if(await data.data.code==-1) {
                type_="error"
              }else if(data.data.code==0){
                type_="warning"
              }else if(data.data.code==1){
                type_="success"
              }
              this.tableData=await data.data.data
              msg=await data.data.msg
              this.$message({
                type: type_,
                message: msg
              });
            }).catch(function (error) {
              console.log(error);
            });       
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
      }
    },
    addForm(formName){  //添加管理员的方法
      this.$refs[formName].validate( async (valid) => {
        if (valid) {
          let arr=[],ii={key:"",value:""}
          for(let i in this.ruleData){
            console.log(i,this.ruleData[i])
            arr.push('"'+i+'":"'+this.ruleData[i]+'"')
            ii.key=i
            ii.value=this.ruleData[i]
          }
          arr=await '{'+(arr.join(",",","))+'}'
          console.log("输出arr",arr);
          //向后端请求添加数据
          let type_="",msg=""
          this.$axios.post(`api/webTableAddData?name=${this.dataName}&table=${this.tableName}&page=${this.page_index}&number=${this.onepage_number}`,arr).then(async (data)=>{
            if(await data.data.code==-1) {
              type_="error"
            }else if(data.data.code==0){
              type_="warning"
            }else if(data.data.code==1){
              type_="success"
            }
            this.tableData=await data.data.data
            msg=await data.data.msg
            this.addManage = false
            this.$message({
              type: type_,
              message: msg
            });
          }).catch(function (error) {
            console.log(error);
          });       
        } else {
          console.log('error submit!!');
          // return false
        }
      })
    },
    clickPage(page){  //点击页数时
      this.page_index=page

      this.$axios.get(`api/webTableData?name=${this.dataName}&table=${this.tableName}&page=${page}&number=${this.onepage_number}`).then(async (data)=>{
        this.tableData=await data.data.data
        //"id","goods","price","goods_sort","goods_order"
        this.alterArr=[]
        this.TableArr=[]
        this.dateArr=[]
        for(let i in this.tableData[0]){
          console.log(i)
          this.alterArr.push(i)
          this.TableArr.push(i)
          this.dateArr.push(i)
        }
      })
    }

  },
  mounted(){
    console.log("显示状态 ",this.showTable)
    //自适应屏幕长度
    if(window.innerWidth<1100){
        this.table=8
    }else if(window.innerWidth<750){
        this.table=6
    }
    // <!--      数据根据高度穿多少数据，留空给分页         -->
    const hh = window.innerHeight;
    const ww = window.innerWidth;
    let number; //页面每页可传递多少条数据
    number = Math.floor((hh - 111) /55);
    this.onepage_number = number;

    //获取当前网站的数据库中所有的表列出来，然后放到arr中
    this.$EventBus.$off('ShowDataTable')
    this.$EventBus.$on("ShowDataTable",(value)=>{
      this.dataName=value
      console.log("显示数据库",value)
      this.$axios.get("api/webTableName?name="+value).then(async (data)=>{
        this.alterArr=[]
        this.TableArr=[]
        this.dateArr=[]
        this.showTable=true
        this.table_arr=[data.data]
        console.log(this.table_arr)
          // "goods","user","order","shopping","goods_sort","order_status"
      })
    })

    setTimeout(()=>{
      this.data_loading=false  //关闭加载骨架
    },0)

  },

}
</script>

<style lang="scss">

.data {
  overflow-y: scroll;
  height: 86vh;
  &::-webkit-scrollbar {
    display: none;
    width: 0;
    height: 0;
    color: transparent;
  }
}

.margin_top {
    margin: 30px 0;
    img{
        width: 128px;
        height: 128px;
    }
    img,p {
        cursor: pointer;
    }
    p{
      width: 128px;
      margin: 0 auto;
    }
}
.el-table--enable-row-hover .el-table__body tr:hover > td.el-table__cell {
  background: #5aa4ae !important;
  font-weight: bold;
  color: white;
}
.el-table__body tr.current-row > td.el-table__cell {
  background: #5aa4ae !important;
  font-weight: bold;
  color: white;
}
.botton_xiu {
  background: #003d74;
  color: white;
  border: 0;
  &:hover {
    background: #0157a1;
  }
}
.el-button {
  margin: 0 10px;
  padding: 10px 18px;
}
.someDelete{
  z-index: 30;
  padding: 9px 50px;
  font-size: 15px;
  right: 5%;
  position: absolute;
  bottom:2%;
}
.add {
  z-index: 30;
  border: 0;
  padding: 9px 50px;
  font-size: 15px;
  right: calc(10% + 130px);
  background: #5aa4ae;
  position: absolute;
  bottom:2%;
  &:hover {
    background: #0157a1;
  }
  &:focus {
    background: #0157a1;
  }
}
.demo-ruleForm {
  text-align: center;
}
.cell {
  overflow: hidden;
  -webkit-line-clamp: 1;
  line-clamp: 1;
  -webkit-box-orient: vertical;
  box-orient: vertical;
  display: -webkit-box;
  display: box;
}
</style>